package com.gyy.flutter.plugin.flutter_plugin_print_a300.newprint;
import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;


import com.gyy.flutter.plugin.flutter_plugin_print_a300.common.BluetoothUtil;
import com.gyy.flutter.plugin.flutter_plugin_print_a300.common.DeviceUtil;
import com.gyy.flutter.plugin.flutter_plugin_print_a300.common.StringUtil;
import com.gyy.flutter.plugin.flutter_plugin_print_a300.newprint.base.BasePointPrint;
import com.gyy.flutter.plugin.flutter_plugin_print_a300.newprint.base.PrintKey;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by gyy on 2017/2/19. Description 打印服务
 */
public class NewPrintService extends IntentService {

    public static final String TAG = "PrintService2";

    /**
     * PrintService的空构造函数.
     */
    public NewPrintService() {
        super("PrintService");
    }

    /**
     * 打印的数据
     */
    private HashMap printData;

    /**
     * 蓝牙地址
     */
    private String printAddress = "";

    /**
     * 蓝牙名称
     */
    private String printName;


    /**
     * onCreate 1，初始化printer 2，获取当前公司名称.
     */
    @Override
    public void onCreate() {
        super.onCreate();
    }

    /**
     * 1，初始化intent传递过来的数据 2，初始化stateArray，map，results 3，判断蓝牙连接成功，哪种打印机.
     */
    @Override
    protected void onHandleIntent(Intent intent) {
        Log.e("PrintService", "onHandleIntent");

        //初始化intent传递过来的数据
        initData(intent);

        String bluetoothAble = BluetoothUtil.getBluetoothAble();
        //蓝牙错误提示
        if (!StringUtil.isEmpty(bluetoothAble)) {
            Log.e("PrintService", bluetoothAble);
            return;
        }

        //匹配 printAddress的设备
        if (!StringUtil.isEmpty(printAddress)) {
            ArrayList<Map<String, String>> bondedDevices = BluetoothUtil.addressList;
            for (Map<String, String> bondedDevice : bondedDevices) {
                if (printAddress.equals(bondedDevice.get(BluetoothUtil.ADDRESS)))
                    printName = bondedDevice.get(BluetoothUtil.NAME);
            }
        }

        //匹配默认设备
        if (printName == null) {
            Map<String, String> defaultPrintDevice = BluetoothUtil.getDefaultPrintDevice();
            if (defaultPrintDevice != null) {
                printAddress = defaultPrintDevice.get(BluetoothUtil.ADDRESS);
                printName = defaultPrintDevice.get(BluetoothUtil.NAME);
            } else {
                //蓝牙连接界面
                toBluetoothConnect();
                return;
            }
        }
        //匹配设备成功
        if (!StringUtil.isEmpty(printAddress)) {
            try {
                if (DeviceUtil.isHM(printName, printAddress)) { //汉印A300
                    if (connectSuccess(DeviceUtil.A300)) {
                        doPrint(DeviceUtil.A300);
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
                Log.e(getClass().toString(), e.getMessage());
                sendErrorBroadcast("数据异常");
            }
        } else {
            //蓝牙连接 界面
            toBluetoothConnect();
        }

    }

    /**
     * 初始化intent传递过来的数据.
     */
    private void initData(Intent intent) {
        Bundle mExtras = intent.getExtras();
        //单个打印 - 传数据
        this.printData = (HashMap) mExtras.getSerializable(PrintKey.DATA_JSON);
        //蓝牙地址
        this.printAddress = mExtras.getString(PrintKey.BLUE_ADDRESS);
    }

    private boolean connectSuccess(String deviceName) {
        if (deviceName.contains(DeviceUtil.A300)) {
            int portOpenHM;
            try {
                int i1 = HPRTAndroidSDKA300.HPRTPrinterHelper.getstatus();
                if (i1 == 0) {
                    Log.e(TAG, "0-portOpenHM= " + i1);
                    return true;
                }
                int i2 = HPRTAndroidSDKA300.HPRTPrinterHelper.getstatus();
                Log.e(TAG, "0-portOpenHM= " + i1 + " " + i2);
                if (i1 == i2 && i1 != -1) {
                    return true;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            //汉印标签机R-300
            new HPRTAndroidSDKA300.HPRTPrinterHelper(this, HPRTAndroidSDKA300.HPRTPrinterHelper.PRINT_NAME_A300);
            try {
                portOpenHM = HPRTAndroidSDKA300.HPRTPrinterHelper.PortOpen("Bluetooth," + printAddress);
            } catch (Exception e) {
                portOpenHM = -1;
                e.printStackTrace();
            }
            Log.e(TAG, "portOpenHM= " + portOpenHM);
            return portOpenHM == 0 || portOpenHM == -4;

        }

        return false;
    }

    /**
     * 执行打印的代码
     */
    private void doPrint(String deviceName) {
        BasePointPrint basePrint = new BasePointPrint(deviceName);
        basePrint.commonPrint(printData, getBaseContext());
        //关闭设备
        closeDevice(deviceName);
    }

    /**
     * 打印完成 关闭设备连接
     *
     * @param deviceName 设备名称
     */
    private void closeDevice(String deviceName) {


    }


    /**
     * 当连接出错，或数据异常，发送广播到activity.
     *连接错误，请重启打印设备后重试
     */
    void sendErrorBroadcast(String message) {
//        Intent mIntent = new Intent(Constant.TOAST_BROADCAST);
//        //显式广播
//        mIntent.setClass(this, ToastReceive.class);
//        Bundle mBundle = new Bundle();
//        mBundle.putString("message", message);
//        mIntent.putExtras(mBundle);
//        sendBroadcast(mIntent);
    }

    /**
     * 跳转到蓝牙连接界面
     */
    private void toBluetoothConnect() {

//        Intent startIntent = new Intent(this, BluetoothConnectActivity.class);
//        startIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        startActivity(startIntent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
